<template>
  <el-card style="max-width: 1200px;margin: auto;">
    <template #header>
      <div>
        <span>添加内容</span>
      </div>
    </template>
    <el-form :model="formData" ref="formRef" :rules="rules" label-position="left" label-width="110px" size="default"
      @submit.prevent>
      <el-form-item label="标题" prop="title" class="required label-right-align">
        <el-input v-model="formData.title" type="text" clearable></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="category" class="required label-right-align">
        <el-input v-model="formData.category" type="text" clearable></el-input>
      </el-form-item>
      <el-form-item label="访问地址" prop="url" class="required label-right-align">
        <el-input v-model="formData.url" type="text" clearable></el-input>
      </el-form-item>
      <el-form-item label="上传封面图 / 输入封面地址">
        <div style="display: flex;width: 100%;">
          <div>
            <el-upload :file-list="fileList" action="/api/upload/libraries/single" :on-progress="handleProgress"
              :on-success="handleSuccess" :on-error="handleError" ref="uploadComm" :show-file-list="false"
              :loading="isUploading">
              <el-button type="primary" v-if="formData.imgUrl">修改封面</el-button>
              <el-button type="primary" v-else>上传封面</el-button>
              <template #tip>
                <div class="el-upload__tip">图片不能大于500kb</div>
              </template>
            </el-upload>
          </div>
          <div style="width: 100%;flex: 1;">
            <el-input v-model="formData.img" type="text" placeholder="请输入封面地址" style="width: 100%;"></el-input>
          </div>
        </div>
        <div>
          <img v-if="formData.img" :src="formData.img" class="avatar" @click="handlePictureCardPreview"
            style="max-height:200px">
        </div>
      </el-form-item>
      <el-form-item label="背景底色" prop="bgColor" class="label-right-align">
        <div style="display: flex;">
          <el-input type="color" v-model="formData.bgColor" size="small" placeholder="请选择背景底色" style="width:100px">
          </el-input>
          <el-input v-model="formData.bgColor" type="text" placeholder="请输入背景底色"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="描述" prop="descriptions" class="required label-right-align">
        <el-input type="textarea" v-model="formData.descriptions" rows="3"></el-input>
      </el-form-item>
      <el-form-item label="详细内容" prop="content" class="label-right-align">
        <!-- <vue-editor v-model="formData.content"></vue-editor> -->
        <el-input type="textarea" v-model="formData.content" rows="3"></el-input>
      </el-form-item>
      <el-form-item label="启用状态" prop="status" class="label-right-align">
        <el-switch v-model="formData.status"></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">Create</el-button>
        <el-button>Cancel</el-button>
      </el-form-item>
    </el-form>
  </el-card>

</template>
<script setup>
  import { ElForm, ElFormItem, ElInput, ElDivider, ElUpload, ElSwitch, ElCard, ElButton, ElMessage } from 'element-plus'
  import { reactive, toRefs, ref, onMounted } from 'vue'
  import axios from './../../http/index'

  // 定义组件  
  const formRef = ref(null)
  const fileList = []
  const isUploading = false
  // 定义响应式数据  
  const formData = reactive({
    title: "",
    category: '',
    img: null,
    alt: "",
    url: "",
    descriptions: "",
    content: null,
    bgColor: '#ffffff',
    status: true,
  })

  // 定义校验规则  
  const rules = reactive({
    title: [{ required: true, message: '标题不可为空', trigger: 'blur' }],
    category: [{ required: true, message: '分类不可为空', trigger: 'blur' }],
    url: [{ required: true, message: '访问地址不可为空', trigger: 'blur' }],
    img: [{ required: true, message: '请上传缩略图', trigger: 'change' }],
    descriptions: [{ required: true, message: '描述不可为空', trigger: 'blur' }],
  })

  // 定义其他响应式数据  
  const imgFileList = reactive([])
  const imgUploadHeaders = reactive({})
  const imgUploadData = reactive({})

  // 重置表单函数  
  const resetForm = () => {
    if (formRef) {
      formRef.resetFields();
    }
  };

  // 表单验证函数  
  // 表单验证函数  
  const validateForm = async () => {
    try {
      await formRef.value.validate((valid) => {
        if (!valid) {
          console.log(formRef.value, 'valid')
          // 如果验证失败，通过 ElMessage 显示错误信息  
          formRef.value.validateFields((error, fields) => {
            console.log(error, fields)
            if (error) {
              const errorMsg = Object.values(fields).map(item => item.message).join('；');
              ElMessage({
                message: '表单验证失败: ' + errorMsg,
                type: 'error',
              });
              return false
            }

            return true
          });
        }
      });
    } catch (error) {
      // 如果在验证过程中发生其他错误，显示错误信息  
      ElMessage({
        message: '表单验证过程中发生错误:',
        type: 'error',
      });
      return false
    }
  };

  const onSubmit = async () => {
    try {
      // 验证表单  
      return await validateForm();

      // 如果验证通过，则提交表单  
      const params = { ...formData, alt: formData.title };
      const response = await axios.post('/api/libraries/addLibraries', params);
      if (response.data.code === 0 && response.data.affectedRows > 0) {
        ElMessage({
          message: response.data.msg,
          type: 'success',
        });
        resetForm(formRef); // 重置表单  
      } else {
        ElMessage({
          message: '添加失败: ' + response.data.msg,
          type: 'error',
        });
      }
    } catch (error) {
      if (error.response) {
        // 请求已发出，服务器也响应了状态码  
        ElMessage({
          message: error.response.data.msg || error.response.data,
          type: 'error',
        });
      } else if (error.request) {
        // 请求已发出，但没有收到任何响应  
        ElMessage({
          message: '请求失败，未收到响应',
          type: 'error',
        });
      } else {
        // 发送请求时发生了些事情，但并未触发错误处理  
        ElMessage({
          message: '请求出错: ' + error.message,
          type: 'error',
        });
      }
    }
  };
  const handleProgress = () => { }
  const handleSuccess = () => { }
  const handleError = () => { }

  // 导出响应式数据和其他方法  
  defineExpose({
    ...toRefs(formData),
    ...toRefs(rules),
    imgFileList,
    imgUploadHeaders,
    imgUploadData,
    validateForm,
    resetForm,
    onSubmit,
    formRef
  })

</script>


<style lang="scss">
  .el-input-number.full-width-input,
  .el-cascader.full-width-input {
    width: 100% !important;
  }

  .el-form-item--medium {
    .el-radio {
      line-height: 36px !important;
    }

    .el-rate {
      margin-top: 8px;
    }
  }

  .el-form-item--small {
    .el-radio {
      line-height: 32px !important;
    }

    .el-rate {
      margin-top: 6px;
    }
  }

  .el-form-item--mini {
    .el-radio {
      line-height: 28px !important;
    }

    .el-rate {
      margin-top: 4px;
    }
  }

  .clear-fix:before,
  .clear-fix:after {
    display: table;
    content: "";
  }

  .clear-fix:after {
    clear: both;
  }

  .float-right {
    float: right;
  }
</style>

<style lang="scss" scoped>
  div.table-container {
    table.table-layout {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;

      td.table-cell {
        display: table-cell;
        height: 36px;
        border: 1px solid #e1e2e3;
      }
    }
  }

  div.tab-container {}

  .label-left-align :deep(.el-form-item__label) {
    text-align: left;
  }

  .label-center-align :deep(.el-form-item__label) {
    text-align: center;
  }

  .label-right-align :deep(.el-form-item__label) {
    text-align: right;
  }

  .custom-label {}

  .static-content-item {
    min-height: 20px;
    display: flex;
    align-items: center;

    :deep(.el-divider--horizontal) {
      margin: 0;
    }
  }
</style>